package cn.com.gridinfo.sooc.core.expand.callname.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.jeremy.arad.utils.AnimUtil;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;

import org.apache.http.message.BasicNameValuePair;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocActivity;
import cn.com.gridinfo.sooc.core.expand.callname.adapter.CourseMenuAdapter;
import cn.com.gridinfo.sooc.core.expand.callname.bean.ClassInfo;
import cn.com.gridinfo.sooc.core.expand.callname.common.CodeConst;
import cn.com.gridinfo.sooc.core.expand.callname.common.PageConst;
import cn.com.gridinfo.sooc.core.expand.callname.dao.CallNameDao;
import cn.com.gridinfo.sooc.utils.IntentUtil;
import cn.com.gridinfo.sooc.utils.MessageUtils;

/**
 * 学生名单
 *
 * @author yingchunli
 */
public class CourseMenuActivity extends BaseSoocActivity {

    @InjectView(R.id.list_coursemenu)
    UltimateRecyclerView listCourseMenu;//列表数据
    CourseMenuAdapter adapter;//适配器
    LinearLayoutManager linearLayoutManager;//布局管理器
    CallNameDao dao;
    int maxLastPositon;//分页最后位置
    private final int INTENT_ADDCOURSE = 2;//跳转到新增课程界面的常量
    private final int INTENT_STUDENTMENU = 3;//跳转到学生名单界面的常量
    private final int INTENT_MODIFY_COURSE = 4;//跳转到编辑课程界面的常量
    int delPosition;//要删除的课程的位置
    @InjectView(R.id.blank_view)
    RelativeLayout layout;//空白布局

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.expand_callname_coursemenu);
        dao = new CallNameDao(this);
        ButterKnife.inject(this);
        //初始化listView
        linearLayoutManager = new LinearLayoutManager(this);
        listCourseMenu.setLayoutManager(linearLayoutManager);
        //发送请求，获取列表数据
        PageConst.pageNo = 1;
        PageConst.pageSize = 10;
        dao.getTongjiList(PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_TONGJI_FRIST);
    }

    /**
     * 无数据时，空白页设置
     */
    void setBlankView() {
        layout.setVisibility(View.VISIBLE);
        ImageView imageView = (ImageView) findViewById(R.id.blank_icon);
        TextView textView = (TextView) findViewById(R.id.tipBlank);
        imageView.setImageResource(R.mipmap.blank_course);
        textView.setText("还没有添加课程哦！");
    }

    /**
     * 初始化数据
     */
    private void initView() {
        adapter = new CourseMenuAdapter(dao.getClassInfoList(), this);
        listCourseMenu.setAdapter(adapter);
        listCourseMenu.enableLoadmore();
        listCourseMenu.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                PageConst.pageNo = 1;//首页
                dao.getTongjiList(PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_TONGJI_PUSHDOWN);
                linearLayoutManager.scrollToPosition(0);
            }
        });
        listCourseMenu.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore(final int itemsCount, final int maxLastVisiblePosition) {
                if (itemsCount > (PageConst.pageSize - 1)) {
                    maxLastPositon = maxLastVisiblePosition;
                    dao.getTongjiList(++PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_TONGJI_PULLUP);
                } else {
                    if (listCourseMenu != null) {
                        adapter.loadNoDataView();
                    }
                    linearLayoutManager.scrollToPositionWithOffset(maxLastVisiblePosition, -1);
                }
            }
        });
        //list 的 item 点击事件
        adapter.setmOnItemClickLitener(new CourseMenuAdapter.OnItemClickListener() {

            @Override
            public void OnItemClick(final ClassInfo classInfo, int position) {
                //编辑课程
                delPosition = position;
                new MaterialDialog.Builder(CourseMenuActivity.this)
                        .items(R.array.edit_course)
                        .backgroundColor(getResources().getColor(R.color.white))
                        .contentColor(getResources().getColor(R.color.color_tv333))
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {

                                if (text.toString().equals("编辑课程")) {

                                    //编辑课程
                                    IntentUtil.intentSlidIn(CourseMenuActivity.this, ModifyCourseActivity.class,
                                            INTENT_MODIFY_COURSE, new BasicNameValuePair("kcid", classInfo.getKcid()),
                                            new BasicNameValuePair("kcmc", classInfo.getKcmc()),
                                            new BasicNameValuePair("skxq", classInfo.getSkxq()));
                                } else {

                                    //删除课程
                                    dao.delCourse(classInfo.getKcid(), CodeConst.EXPAND_DEL_COURSE);
                                }
                            }
                        })
                        .show();
            }

            @Override
            public void OnItemClick(ClassInfo classInfo) {
                // 跳转到学生名单界面
                Intent intent = new Intent(CourseMenuActivity.this, StudentMenuActivity.class);
                //参数
                intent.putExtra("kcmc", classInfo.getKcmc());
                intent.putExtra("skxq", classInfo.getSkxq());
                intent.putExtra("kcid", classInfo.getKcid());
                startActivityForResult(intent, INTENT_STUDENTMENU);
                AnimUtil.intentSlidIn(CourseMenuActivity.this);
            }
        });
    }

    /**
     * 网络请求数据成功
     *
     * @param requestCode 网络请求顺序号，第一个请求，NetRequestOrderNum=0,处理第一条请求的结果。如果等于1,
     */
    @Override
    public void onRequestSuccess(int requestCode) {
        try {
            if (dao.getStatus().equals("0")) {
                switch (requestCode) {
                    case CodeConst.EXPAND_GET_TONGJI_FRIST:
                        //获取列表数据 首次请求
                        initView();
                        if (dao.getClassInfoList() != null && !dao.getClassInfoList().isEmpty()) {
                            layout.setVisibility(View.GONE);
                        } else {
                            //无数据处理
                            setBlankView();
                        }
                        break;
                    case CodeConst.EXPAND_GET_TONGJI_PUSHDOWN:
                        //下拉请求 刷新操作
                        adapter.refresh(dao.getClassInfoList());
                        if (dao.getClassInfoList() != null && !dao.getClassInfoList().isEmpty()) {
                            listCourseMenu.hideEmptyView();
                            layout.setVisibility(View.GONE);
                        } else {
                            //无数据处理
                            setBlankView();
                        }
                        if (dao.getClassInfoList().size() > (PageConst.pageSize - 1)) {
                            adapter.loadMoreDataView();
                        } else {
                            //数据小于当前页的话则不显示加载更多
                            adapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                            linearLayoutManager.scrollToPosition(maxLastPositon);
                        }
                        break;
                    case CodeConst.EXPAND_GET_TONGJI_PULLUP:
                        //上拉加载 请求数据成功
                        if (dao.getClassInfoList() != null && !dao.getClassInfoList().isEmpty()) {
                            adapter.loadmore(dao.getClassInfoList());
                        } else {
                            //无数据则不显示下一页
                            adapter.loadNoDataView();
                            linearLayoutManager.scrollToPositionWithOffset(maxLastPositon, -1);
                        }
                        break;
                    case CodeConst.EXPAND_DEL_COURSE:
                        //删除课程
                        MessageUtils.showRightImageShortToast(this, "删除成功");
                        adapter.delete(delPosition);
                        if (adapter.getIsLoadMore()) {
                            if (adapter.getAdapterItemCount() < PageConst.pageSize) {
                                //下拉刷新  账户明细数据
                                PageConst.pageNo = 1;//首页
                                dao.getTongjiList(PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_TONGJI_PUSHDOWN);
                                linearLayoutManager.scrollToPosition(0);
                            }
                        }
                        break;
                }
            } else {
                MessageUtils.showImageShortToast(this, dao.getStatusCode());
            }
        } catch (Exception e) {
            MessageUtils.showImageShortToast(this, "请求数据异常");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case INTENT_ADDCOURSE:
                //从新增课程界面返回，更新列表
                //发送请求，获取列表数据
                PageConst.pageNo = 1;
                dao.getTongjiList(PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_TONGJI_FRIST);
                break;
            case INTENT_STUDENTMENU:
                //从学生名单界面返回  刷界面
                PageConst.pageNo = 1;
                dao.getTongjiList(PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_TONGJI_PUSHDOWN);
                break;
            case INTENT_MODIFY_COURSE:
                //从编辑课程界面返回，更新列表
                PageConst.pageNo = 1;
                dao.getTongjiList(PageConst.pageNo, PageConst.pageSize, CodeConst.EXPAND_GET_TONGJI_PUSHDOWN);
                break;
        }
    }

    /**
     * 创建课程的点击
     */
    @OnClick(R.id.createCouse)
    void onclick() {
        //跳转到新增课程页面
        startActivityForResult(new Intent(this, AddCourseActivity.class), INTENT_ADDCOURSE);
        AnimUtil.intentSlidIn(CourseMenuActivity.this);
    }

    @Override
    public String setupToolBarTitle() {
        return "课程管理";
    }

    @Override
    public boolean setupToolBarLeftButton(ImageView leftButton) {
        return true;
    }

    @Override
    public boolean setupToolBarRightButton(ImageView rightButton) {
        return false;
    }

    //Toolbar左侧图标点击  回退键
    @OnClick(R.id.toolbar_leftbtn)
    void onToolbarLeftClick() {
        finish();
    }

}
